'use strict';
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
const GridStore = require('mongodb').GridStore;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const inspect = require('util').inspect;
const gm = require("gm");
module.exports = {
  open: true,
  handler:(req, res, next)=> {
    const collection = req.mongo.collection('fs.files');
    const id = req.params.id;//文件id
    //查找文件信息
    collection.findOne({_id: id}, function (err, data) {
      if (err) return next(err);
      if (!data) return next("not found");
      console.log(data)
      var gfs = Grid(req.mongo, mongo);

      //如果已存在，直接输出，没有则创建输出
      if (data.thumb) {
        console.log("直接输出略缩图");
        gfs.createReadStream({_id: data.thumb, mode: 'r'}).pipe(res);
        return;
      }

      var options = {_id: id};
      //判断文件是否存在
      gfs.exist(options, function (err, found) {
        if (err) return next(err);
        if (!found)  return res.status(404).send();
        //读取文件流
        var readstream = gfs.createReadStream(options);
        //定义写文件流
        var thumbId = new ObjectID();
        var writestream = gfs.createWriteStream({
          _id: thumbId,
          mode: "w",
          filename: data.filename,
          content_type: data.contentType,
          metadata: {thumb: true}
        });
        //处理略缩图，写入gridfs文件系统

        gm(readstream).resize('120', '120').stream().on('end', function () {
          readstream = null;
          writestream = null;
          //写入完成，更新源文件的略缩图标记
          collection.update({_id: id}, {$set: {"thumb": thumbId}}, function () {
          });
          //输出略缩图流
          setTimeout(function () {
            gfs.createReadStream({_id: thumbId, mode: 'r'}).pipe(res);
          }, 300)

        }).pipe(writestream);
      })
    });
  }
};
